﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace WpfConsole
{
    public delegate void Selection(Rect coord, Rect region);

    public class MouseSelection
    {
        int _fontWidth;
        int _fontHeight;

        public bool Selecting { get; set; }
        public bool HasSelection { get; set; }
        public Rect Coord { get; set; }
        public Rect Region { get; set; }

        public MouseSelection(int fontWidth, int fontHeight)
        {
            _fontWidth = fontWidth;
            _fontHeight = fontHeight;
            Selecting = false;
            HasSelection = false;
        }

        internal Rect CreateGridCoord(Point start, Point end)
        {
            return new Rect(
                new Point((int) start.X / _fontWidth,(int) start.Y / _fontHeight),
                new Point((int)end.X / _fontWidth, (int) end.Y / _fontHeight));
        }

        internal Rect CreateRegion(Point start, Point end)
        {
            Rect coord = CreateGridCoord(start, end);
            return new Rect(new Point(coord.Left * _fontWidth, coord.Top * _fontHeight),
                new Point((coord.Right + 1) * _fontWidth, (coord.Bottom + 1) * _fontHeight));
        }

        Point _startPoint;

        public void MouseDown(Point p)
        {
            Selecting = true;
            _startPoint = p;
            OnSelecting(_startPoint, _startPoint);
        }

        private void OnSelecting(Point startPt, Point endPt)
        {
            HasSelection = true;
            Coord = CreateGridCoord(startPt, endPt);
            Region = CreateRegion(startPt, endPt);
            if (SelectionChanged != null)
            {
                SelectionChanged(Coord, Region);
            }
        }

        public void MouseMove(Point p)
        {
            if (Selecting)
            {
                OnSelecting(_startPoint, p);
            }
        }

        public event Selection SelectionChanged;

        public void MouseUp(Point p)
        {
            if (Selecting)
            {
                Selecting = false;
                OnSelecting(_startPoint, p);
            }
        }

        public void Clear()
        {
            Selecting = false;
            HasSelection = false;
        }
    }

}
